package com.gm.commonlib.util.fileUtil;
import java.io.BufferedReader;
import java.io.Closeable;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;

public class StreamUtil {

	public static void scanStream(InputStream fis, OnStreamScanListener l) {
		if (l != null) {
			try {
				l.onScanStart();
				byte[] buffer = new byte[10240];
				int readSize = 0;
				long handleCount = 0;
				while (-1 != (readSize = fis.read(buffer, 0, buffer.length))) {
					l.onStreamScan(buffer, 0, readSize, handleCount += readSize);
				}
				l.onScanEnd(handleCount);
			} catch (Exception e) {
				l.onExceptionOccuerd(e);
			} finally {
				l.onFinish();
			}
		} else {
			System.err.println("没有设置流扫描监听");
		}
	}

	/**
	 * 流转换为字符串
	 *
	 * @param in
	 * @return
	 * @throws IOException
	 */
	public static  String convertStreamToString(InputStream in) throws IOException {
		StringBuilder sb = new StringBuilder();
		BufferedReader r = new BufferedReader(new InputStreamReader(in), 1024);
		for (String line = r.readLine(); line != null; line = r.readLine()) {
			sb.append(line);
		}
		return sb.toString();
	}

	public static void close(Closeable closeable) {
        if(closeable != null) {
            try {
                closeable.close();
            } catch (IOException e) {
            }
        }
    }

	public interface OnStreamScanListener {
		void onScanStart() throws IOException;

		void onStreamScan(byte[] buffer, int offset, int len, long handleCount) throws IOException;

		void onScanEnd(long handleCount) throws IOException;

		void onExceptionOccuerd(Exception e);

		void onFinish();
	}

	public static class FileStreamScanListener implements OnStreamScanListener {

		File targetFile = null;
		OutputStream stream = null;

		public FileStreamScanListener(File file) {
			targetFile = file;
			stream = null;
		}

		@Override
		public void onScanStart() throws IOException {
			if(stream != null) {
				return;
			}

			if(targetFile == null) {
				throw new IOException("targetFile is null!");
			}
			stream = new FileOutputStream(targetFile);
		}

		@Override
		public void onStreamScan(byte[] buffer, int offset, int len, long handleCount) throws IOException {
			stream.write(buffer, offset, len);
		}

		@Override
		public void onScanEnd(long handleCount) throws IOException {
		}

		@Override
		public void onExceptionOccuerd(Exception e) {
			e.printStackTrace();
		}

		@Override
		public void onFinish() {
			StreamUtil.close(stream);
			stream = null;
		}
	}


}
